package com.wnxy.sdd.job;

import com.wnxy.sdd.common.constant.RedisCommon;
import com.wnxy.sdd.config.OssTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class OssDeleteJobTask {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private OssTemplate ossTemplate;
    /**
     * 删除阿里云无效图片
     */
    //@Scheduled(cron = "0 0/2 * * * ?")
    @Scheduled(cron = "0 8 1 * * ?")
    public void execute(){
        System.out.println("=========================" + LocalDateTime.now());
        // 计算set集合的差集，差集就是无效图片，也是要删除的图片
        Set<String> deleteFiles = stringRedisTemplate.opsForSet().difference(
                RedisCommon.ALL_IMAGE, RedisCommon.DB_IMAGE
        );
        // 判断
        if (deleteFiles != null && deleteFiles.size() > 0) {
            System.out.println("=========================删除文件：" + deleteFiles);
            // Set --> List
            List<String> list = new ArrayList<>(deleteFiles);
            // 删除阿里云无效图片
            ossTemplate.deleteFiles(list);

            // 删除Redis中的all_image里面的无效图片
            // 因为阿里云上的无效图片删除了，Redis中也需要删除
            stringRedisTemplate.opsForSet().remove(
                    RedisCommon.ALL_IMAGE,list.toArray()
            );
        }
    }
}
